<template>
  <div class="work-detail-page">
    <!-- 顶部导航 -->
    <header class="header">
      <div class="container">
        <button class="back-btn" @click="goBack">
          <i class="el-icon-arrow-left"></i> 返回
        </button>
        <h1 class="logo">视觉作品库</h1>
        <div class="user-actions">
          <button class="action-btn">
            <i class="el-icon-share"></i>
          </button>
          <button class="action-btn">
            <i class="el-icon-star-on"></i>
          </button>
        </div>
      </div>
    </header>

    <!-- 主要内容区 -->
    <main class="main-content">
      <div class="container">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-state">
          <el-skeleton :rows="5" animated />
        </div>

        <!-- 错误状态 -->
        <div v-else-if="error" class="error-state">
          <h2>{{ error }}</h2>
          <button class="back-btn" @click="goBack">返回上一页</button>
        </div>

        <!-- 作品详情卡片 -->
        <div v-else class="work-card">
          <div class="work-hero">
            <img 
              :src="work.cover || '/default-cover.png'" 
              alt="作品图片" 
              class="work-image"
            >
          </div>

          <div class="work-info">
            <h2 class="work-title">{{ work.title }}</h2>
            
            <!-- 作者信息 -->
            <div class="author-info" @click="goToAuthorPage(work.author?.id)">
              <img 
                :src="work.author?.avatar || '/default-avatar.png'" 
                alt="作者头像" 
                class="author-avatar"
              >
              <div class="author-meta">
                <h4 class="author-name">{{ work.author?.nickname || '未知用户' }}</h4>
                <span class="publish-time">{{ formatTime(work.createdAt) }}</span>
              </div>
            </div>

            <!-- 内容 -->
            <div class="work-content">
              {{ work.content }}
            </div>

            <!-- 标签 -->
            <div class="work-tags" v-if="work.tags && work.tags.length">
              <span class="tag" v-for="tag in work.tags" :key="tag">#{{ tag }}</span>
            </div>

            <!-- 统计信息 -->
            <div class="work-stats">
              <div class="stat-item">
                <i class="el-icon-view"></i>
                <span>{{ work.views }} 浏览</span>
              </div>
              <div class="stat-item" @click="handleLike">
                <i class="el-icon-star-on" :class="{ active: isLiked }"></i>
                <span>{{ work.likes }} 点赞</span>
              </div>
              <div class="stat-item">
                <i class="el-icon-chat-line-round"></i>
                <span>{{ work.comments?.length || 0 }} 评论</span>
              </div>
            </div>

            <!-- 评论区 -->
            <div class="comments-section">
              <h3 class="section-title">评论</h3>
              <CommentSection 
                :targetType="'post'"
                :targetId="work._id"
              />
            </div>
          </div>
        </div>

        <!-- 相关推荐 -->
        <div class="related-works">
          <h3 class="section-title">相关作品</h3>
          <div class="works-grid">
            <div 
              class="related-work" 
              v-for="(item, index) in relatedWorks" 
              :key="index"
            >
              <img 
                :src="item.cover" 
                alt="相关作品" 
                class="related-image"
              >
              <div class="work-meta">
                <h4>{{ item.title }}</h4>
                <span>{{ item.author.name }}</span>
              </div>
            </div>
          </div>

          <!-- 相关作品为空时的提示 -->
          <div v-if="relatedWorks.length === 0" class="empty-related">
            <p>暂无相关作品</p>
          </div>
        </div>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="footer">
      <div class="container">
        <p>© 2023 视觉作品库 | 版权所有</p>
      </div>
    </footer>
  </div>
</template>

<script setup>
import CommentSection from '@/components/common/CommentSection.vue';
import { post } from '@/utils/api';
import { ElMessage } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const router = useRouter();
const route = useRoute();

// 状态管理
const work = reactive({
  title: "",
  cover: "",
  category: "",
  views: 0,
  likes: 0,
  content: "",
  author: null,
  tags: [],
  createdAt: null
});

const loading = ref(false);
const error = ref(null);
const isLiked = ref(false);
const relatedWorks = ref([]); // 相关作品

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: 'numeric',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 加载作品详情
const loadWorkDetail = async (id) => {
  loading.value = true;
  error.value = null;
  try {
    if (!id) {
      throw new Error('无效的作品ID');
    }

    const response = await post.getById(id);
    if (!response || !response.data) {
      throw new Error('获取作品详情失败');
    }

    // 更新 work 数据
    const data = response.data.data;
    Object.assign(work, data);
    // 设置点赞状态
    isLiked.value = data.isLiked || false;

  } catch (err) {
    console.error('加载作品详情失败:', err);
    error.value = err.message || '加载作品失败';
  } finally {
    loading.value = false;
  }
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 跳转到作者主页
const goToAuthorPage = (authorId) => {
  if (authorId) {
    router.push(`/user/${authorId}`);
  }
};

// 处理点赞
const handleLike = async () => {
  try {
    const res = await post.toggleLike(route.params.id);
    if (res.data && res.data.data) {
      isLiked.value = res.data.data.isLiked;
      work.likes = res.data.data.likes;
      ElMessage.success(res.data.message);
    }
  } catch (error) {
    console.error('点赞失败:', error);
    ElMessage.error(error.message || '操作失败');
  }
};

// 初始化加载
onMounted(() => {
  const id = route.params.id;
  loadWorkDetail(id);
});
</script>

<style scoped>
.work-detail-page {
  background: #f8f9fa;
  min-height: 100vh;
  padding-top: 64px;  /* 为固定头部留出空间 */
}

/* 顶部导航 */
.header {
  background: #fff;
  padding: 12px 0;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.back-btn {
  background: none;
  border: none;
  font-size: 1.1rem;
  color: #333;
  cursor: pointer;
  padding: 8px 12px;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.2s ease;
}

.back-btn:hover {
  color: #42b983;
}

.logo {
  font-size: 1.4rem;
  font-weight: 600;
}

.user-actions {
  display: flex;
  gap: 16px;
}

.action-btn {
  background: none;
  border: none;
  font-size: 1.2rem;
  color: #666;
  cursor: pointer;
  padding: 8px;
  transition: all 0.2s ease;
}

.action-btn:hover {
  color: #42b983;
}

/* 作品展示区 */
.work-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  margin: 20px auto;
  max-width: 1200px;
  overflow: hidden;
}

.work-hero {
  width: 100%;
  height: 0;
  padding-bottom: 56.25%;
  position: relative;
  background: #f5f5f5;
}

.work-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.work-info {
  padding: 24px;
}

.work-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 16px;
  color: #333;
}

.author-info {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  cursor: pointer;
}

.author-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  margin-right: 12px;
  object-fit: cover;
}

.author-meta {
  flex: 1;
}

.author-name {
  font-size: 16px;
  font-weight: 500;
  margin: 0;
  color: #333;
}

.publish-time {
  font-size: 14px;
  color: #999;
}

.work-content {
  font-size: 16px;
  line-height: 1.8;
  color: #333;
  margin: 24px 0;
}

.work-tags {
  margin: 16px 0;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.tag {
  padding: 4px 12px;
  background: #f5f5f5;
  border-radius: 16px;
  font-size: 14px;
  color: #666;
}

.work-stats {
  display: flex;
  gap: 24px;
  padding: 16px 0;
  border-top: 1px solid #eee;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #666;
  cursor: pointer;
  transition: color 0.2s;
}

.stat-item:hover {
  color: #409EFF;
}

.stat-item i {
  font-size: 18px;
}

.stat-item .active {
  color: #409EFF;
}

.comments-section {
  margin-top: 24px;
  padding: 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 16px;
  color: #333;
}

/* 加载状态 */
.loading-state {
  padding: 32px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  margin-bottom: 24px;
}

/* 错误状态 */
.error-state {
  padding: 48px;
  text-align: center;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  margin-bottom: 24px;
}

.error-state h2 {
  color: #f56c6c;
  margin-bottom: 24px;
  font-size: 1.5rem;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .work-info {
    padding: 16px;
  }
  
  .work-title {
    font-size: 1.4rem;
  }
  
  .author-info {
    margin: 16px 0;
  }
  
  .comments-section {
    padding: 16px;
  }
}
</style>